package com.gjy.disruptor.uuid.newd.netty;

import com.gjy.disruptor.uuid.newd.dis.UuidEventProducer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-10-11 10:21:27
 */
public class HttpUuidServer {

    private static final Logger logger = LoggerFactory.getLogger(HttpUuidServer.class);

    private final int port;
    private final UuidEventProducer producer;

    public HttpUuidServer(int port) {
        this.port = port;
        this.producer = new UuidEventProducer();
    }

    public void run() throws InterruptedException {
        // 优化线程组配置
        EventLoopGroup bossGroup;
        EventLoopGroup workerGroup;
        Class<? extends ServerChannel> channelClass;

        if (Epoll.isAvailable()) {
            bossGroup = new EpollEventLoopGroup(2);
            workerGroup = new EpollEventLoopGroup(Math.max(4, Runtime.getRuntime().availableProcessors() * 4));
            channelClass = EpollServerSocketChannel.class;
            logger.info("Using Epoll native transport.");
        } else {
            bossGroup = new NioEventLoopGroup(2);
            workerGroup = new NioEventLoopGroup(Math.max(4, Runtime.getRuntime().availableProcessors() * 4));
            channelClass = NioServerSocketChannel.class;
            logger.info("Using Nio transport.");
        }

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(channelClass)
                    .option(ChannelOption.SO_BACKLOG, 8192)
                    .option(ChannelOption.SO_REUSEADDR, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childOption(ChannelOption.SO_RCVBUF, 131072)
                    .childOption(ChannelOption.SO_SNDBUF, 131072)
                    .childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
                            new WriteBufferWaterMark(32 * 1024, 64 * 1024))
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new IdleStateHandler(60, 30, 120)); // 读60秒，写30秒，全120秒
                            // HTTP编解码器
                            p.addLast(new HttpServerCodec());
                            // 将HTTP消息聚合成FullHttpRequest/FullHttpResponse
                            p.addLast(new HttpObjectAggregator(65536));
                            // 自定义的请求处理逻辑
                            p.addLast(new UuidRequestHandler(producer));
                        }
                    });

            // 绑定端口，开始接收连接
            ChannelFuture f = b.bind(port).sync();

            logger.info("UUID Server started, listening on port {}", port);

            // 等待服务器套接字关闭
            f.channel().closeFuture().sync();
        } finally {
            // 优雅地关闭线程组
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            producer.shutdown();
            logger.info("UUID Server stopped.");
        }
    }

}
